const Contact = require("../model/contact.model");
const { Op } = require("sequelize");
class ContactService {
  // 创建联系人地址
  async insertAddress(
    contact_name,
    contact_phone,
    user_id,
    province,
    city,
    county,
    address_detail,
    is_default
  ) {
    if (is_default === "1") {
      await Contact.update(
        {
          is_default: "0",
        },
        {
          where: {
            user_id,
            is_default: "1",
          },
        }
      );
    }
    const result = await Contact.create({
      contact_name,
      contact_phone,
      user_id,
      province,
      city,
      county,
      address_detail,
      is_default,
    });
    return result;
  }

  // 查询联系人地址列表
  async getAddressList(user_id) {
    const result = await Contact.findAll({
      where: {
        user_id,
      },
    });
    return result;
  }

  // 查询单个联系人地址
  async getOneAddress({ contact_id, user_id }) {
    if (user_id) {
      const result = await Contact.findOne({
        where: {
          is_default: "1",
          user_id,
        },
      });

      return result;
    } else {
      const result = await Contact.findOne({
        where: {
          contact_id,
        },
      });
      return result;
    }
  }

  // 更新联系人地址
  async update2Address(
    contact_name,
    contact_phone,
    user_id,
    province,
    city,
    county,
    address_detail,
    is_default,
    contact_id
  ) {
    if (is_default === "1") {
      await Contact.update(
        {
          is_default: "0",
        },
        {
          where: {
            user_id,
            is_default: "1",
          },
        }
      );
    }
    const result = await Contact.update(
      {
        contact_name,
        contact_phone,
        user_id,
        province,
        city,
        county,
        address_detail,
        is_default,
      },
      {
        where: {
          contact_id,
        },
      }
    );
    return result;
  }
  // 删除联系人地址
  async remove2Address(contact_id) {
    const result = await Contact.destroy({
      where: {
        contact_id,
      },
    });
    return result;
  }
}

module.exports = new ContactService();
